package k8s

import (
	"context"

	"github.com/sirupsen/logrus"
	"k8s.io/apimachinery/pkg/labels"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var (
	ExitCodeReason = map[int32]string{
		0:   "正常退出",
		1:   "应用错误",
		2:   "内建命令错误",
		126: "命令调用错误",
		127: "找不到文件或目录",
		128: "退出时使用的参数无效",
		129: "退出并接收到 SIGHUP",
		130: "退出并接收到 SIGINT",
		131: "退出并接收到 SIGQUIT",
		132: "退出并接收到 SIGILL",
		133: "退出并接收到 SIGTRAP",
		134: "异常终止 (SIGABRT)",
		135: "退出并接收到 SIGBUS",
		136: "退出并接收到 SIGFPE",
		137: "立即终止 (SIGKILL)",
		138: "退出并接收到 SIGUSR1",
		139: "分段错误 (SIGSEGV)",
		140: "退出并接收到 SIGUSR2",
		141: "退出并接收到 SIGPIPE",
		142: "退出并接收到 SIGALRM",
		143: "优雅终止 (SIGTERM)",
		144: "退出并接收到 SIGSTKFLT",
		145: "退出并接收到 SIGCHLD",
		146: "退出并接收到 SIGCONT",
		147: "退出并接收到 SIGSTOP",
		148: "退出并接收到 SIGTSTP",
		149: "退出并接收到 SIGTTIN",
		150: "退出并接收到 SIGTTOU",
		255: "退出状态超出范围",
	}
)

func (k *K8sClient) ListPodsByLables(namespace string, labelsMap map[string]string) ([]corev1.Pod, error) {
	options := metav1.ListOptions{
		LabelSelector: labels.SelectorFromSet(labelsMap).String(),
		// FieldSelector: fields.ParseSelectorOrDie("status.phase=Running").String(),
	}

	pods, err := k.Clientset.CoreV1().Pods(namespace).List(context.TODO(), options)
	if err != nil {
		return nil, err
	}

	return pods.Items, nil
}

func (k *K8sClient) GetPodExitMessageByEvent(e *corev1.Event) string {
	podInfo, err := k.Clientset.CoreV1().Pods(e.Namespace).Get(context.TODO(), e.InvolvedObject.Name, metav1.GetOptions{})
	if err != nil {
		logrus.Errorf("Failed to get pod message from event %v: %s", *e, err.Error())
		return ""
	}

	containerStatus := podInfo.Status.ContainerStatuses[0].LastTerminationState.Terminated

	if containerStatus != nil {
		return containerStatus.Reason
	}

	return ""
}
